import { queryConfigBykey, saveConfig } from "@/api/config";
import { uploadFile } from "@/api/file";
import { LOVE_INFO_KEY } from "@/constants/configKey.constant";
import { ConfigType } from "@/types/config";
import { deleteFileInf } from "@/utils/deleteFileInf";
import { message, UploadFile } from "antd";
import { useForm } from "antd/es/form/Form";
import { useState, useCallback, useEffect } from "react";
import dayjs from 'dayjs'
export type FieldType = {
    manName: string
    womanName: string
    womanAvatar: string
    manAvatar: string
    heart: string
    timing?: string
    bg: string
};
type ImgType = 'manAvatar' | 'womanAvatar' | 'heart' | 'bg'
export const useBasicInfo = () => {
    const [loading, setLoading] = useState(false);
    const [btnLoading, setBtnLoading] = useState(false);
    const [messageApi] = message.useMessage();
    const [fileList, setFileList] = useState<Record<ImgType, UploadFile[]>>({
        manAvatar: [],
        womanAvatar: [],
        heart: [],
        bg: []
    })
    const [form] = useForm();
    const [configInfo, setConfigInfo] = useState<ConfigType.Row<FieldType>>({
        id: "",
        title: "",
        configKey: "",
        config: {
            manName: '',
            womanName: '',
            womanAvatar: '',
            manAvatar: '',
            heart: '',
            timing: '',
            bg: '',
        },

    });
    const getConfig = useCallback(async () => {
        setLoading(true);
        const res = await queryConfigBykey(LOVE_INFO_KEY);
        setLoading(false);
        if (res.code === 200) {
            const obj = res.data || {};
            const config = obj.config ? JSON.parse(obj.config) : {};
            setConfigInfo({
                id: obj.id,
                title: obj.title,
                configKey: obj.configKey,
                config,
            });

            form.setFieldsValue({
                ...config,
                timing:config.timing?dayjs(config.timing):dayjs()
            });
            setFileList({
                manAvatar: config.manAvatar ? [
                    {
                        uid: "manAvatar",
                        name: "manAvatar",
                        status: "done",
                        url: config.manAvatar,
                    }
                ] : [],
                womanAvatar: config.womanAvatar ? [
                    {
                        uid: "womanAvatar",
                        name: "womanAvatar",
                        status: "done",
                        url: config.womanAvatar,
                    }
                ] : [],
                heart: config.heart ? [{
                    uid: "heart",
                    name: "heart",
                    status: "done",
                    url: config.heart,
                }] : [],
                bg: config.bg ? [{
                    uid: "bg",
                    name: "bg",
                    status: "done",
                    url: config.bg,
                }] : []
            })
            
        }
    }, [form]);

    /**
     * 保存配置
     * @param config
     */
    const saveConfigInf = async (values: FieldType) => {
        const { manName, womanName, timing } = values;
        const manAvatar = fileList.manAvatar[0] && fileList.manAvatar[0].url ? fileList.manAvatar[0].url : "";
        const womanAvatar = fileList.womanAvatar[0] && fileList.womanAvatar[0].url ? fileList.womanAvatar[0].url : "";
        const heart = fileList.heart[0] && fileList.heart[0].url ? fileList.heart[0].url : "";
        const bg = fileList.bg[0] && fileList.bg[0].url ? fileList.bg[0].url : "";
        const config = {
            manName,
            womanName,
            timing:dayjs(timing).format('YYYY-MM-DD HH:mm:ss'),
            manAvatar,
            womanAvatar,
            heart,
            bg
        };
        const params = {
            id: configInfo?.id,
            configKey: LOVE_INFO_KEY,
            config: JSON.stringify(config),
        };
        setBtnLoading(true);
        const res = await saveConfig(params);
        setBtnLoading(false);
        if (res.code === 200) {
            messageApi.success("保存成功");
            getConfig();
        }
    };
    const onFinish = async (values: FieldType) => {
        saveConfigInf(values);
    };


    const uploadFileInf = async (type: ImgType, file: File | string | Blob) => {
        if (typeof file === "string") return;
        const formData = new FormData();
        formData.append("file", file);
        try {
            const res = await uploadFile(formData);
            const url = fileList[type][0] && fileList[type][0].url ? fileList[type][0].url : "";
            if (url) {
                deleteFileInf(url);
            }
            if (res.data) {
                setFileList({
                    ...fileList,
                    [type]: [
                        {
                            uid: type,
                            name: type,
                            status: "done",
                            url: res.data,
                        },
                    ]
                });
            }
        } catch (error) {
            console.error(error);
        }
    };

    useEffect(() => {
        getConfig();
    }, [getConfig]);
    return {
        loading,
        btnLoading,
        form,
        onFinish,
        uploadFileInf,
        fileList,
        setFileList
    }
}